package dao.impl;

import dao.UserDao;
import domain.User;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import utils.JdbcUtils;

import java.util.List;

public class UserDaoImpl implements UserDao {
    private JdbcTemplate template = new JdbcTemplate(JdbcUtils.getDataSource());
    @Override
    public User findThisUser(User loginUser) {
        try {

            String sql = "select * from user where username=? and password=? " ;
            //因为用这个方法查询如果没有拆线呢到,会抛异常,我们必须捕获
            User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), loginUser.getUsername( ), loginUser.getPassword( ));
            return user ;
        } catch (DataAccessException e) {
            //没有查询到结果
            return null ;
        }

    }

    @Override
    public List<User> findAllUser() {
        String sql = "select * from user ";
        List<User> users = template.query(sql, new BeanPropertyRowMapper<User>(User.class));
        return users;
    }

    /**
     *   添加
     * @param user
     */
    @Override
    public void addUser(User user) {
        String sql = "insert into user(name,gender,age,address,qq,email) values(?,?,?,?,?,?)" ;
        template.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail()) ;
    }

    /**
     *  删除
     * @param id
     */
    @Override
    public void removeUser(String id) {
        String sql = "delete from user where id=?" ;
        template.update(sql,id) ;
    }

    /**
     *   查询指定id的用户
     * @param id
     * @return
     */
    @Override
    public User findAssignUser(String id) {
        String sql = "select * from user where id=?";
        try {
            User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id);
            return user ;
        } catch (DataAccessException e) {
            return null ;
        }

    }

    /**
     *   修改用户
     * @param user
     */
    @Override
    public void updateUser(User user) {
        String sql = "update user set name=?,gender=?,age=?,address=?,qq=?,email=? where id=?" ;
        template.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail(),user.getId());
    }

    /**
     * 查询所有数据的个数
     * @return
     */
    @Override
    public int findTotalCount() {
        String sql = "select count(*) from user ";
        Integer totalCount = template.queryForObject(sql, Integer.class);
        return totalCount;
    }

    /**
     *  查询当前页面的数据
     * @param start
     * @param rows
     * @return
     */
    @Override
    public List<User> findList(int start, int rows) {
        String sql = "select * from user limit ?,? ";
        List<User> l = template.query(sql, new BeanPropertyRowMapper<User>(User.class), start, rows);
        return l;
    }
}
